/**
 * @description Login Component
 */

import React, { Component, Fragment } from 'react'
import { Form, Icon, Input, Button, Checkbox, notification, Affix } from 'antd'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import Api from '@api'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'
import Animate from 'rc-animate'

const FormItem = Form.Item

class NormalLogin extends Component {
  static propTypes = {
    form: PropTypes.object,
    history: PropTypes.object,
    intl: intlShape.isRequired
  }
  constructor(props) {
    super(props)
    this.state = {}
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  handleSubmit(e) {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // Check validation
        let param = {}
        param.userName = values.userName
        param.password = values.password
        Api.post('login', param, true).then(res => {
          // Login success
          notification.success({
            message: this.props.intl.formatMessage({
              id: 'i18n_common_success'
            }),
            description: JSON.stringify(res)
          })
          sessionStorage.setItem('ri-login', true)
          this.props.history.push('/dashboard')
        })
      }
    })
  }
  UNSAFE_componentWillMount() {
    // Handle has logined just to dashboard
    sessionStorage.getItem('ri-login') && this.props.history.push('/dashboard')
  }
  // Set language to localStorage
  setLanguage() {
    const curLan = localStorage.getItem('ri-lan')
    localStorage.setItem('ri-lan', curLan === 'en' ? 'zh' : 'en')
    // FIXME: will do smooth reload
    window.location.reload()
  }
  render() {
    const { getFieldDecorator } = this.props.form
    // React-intl Format message function
    const { formatMessage } = this.props.intl
    // Extend class
    const loginClass = classNames(
      'd-flex justify-content-center align-items-center h-100 w-100 bg-login'
    )
    return (
      <Fragment>
        <Affix className="position-absolute adjust-language-position ">
          <Button icon="global" onClick={this.setLanguage}>
            <FormattedMessage id="i18n_login_switch_language_label" />
          </Button>
        </Affix>
        <Animate
          transitionName="fade"
          transitionAppear={true}
          className={loginClass}
        >
          <Form onSubmit={this.handleSubmit} className="login-form">
            <FormItem
              hasFeedback
              validateStatus="validating"
              help={
                <span className="text-secondary">
                  {formatMessage({
                    id: 'i18n_login_validing_label'
                  })}
                </span>
              }
            >
              {getFieldDecorator('userName', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_login_user_name_valid_label'
                    })
                  }
                ]
              })(
                <Input
                  prefix={<Icon type="user" />}
                  placeholder={formatMessage({
                    id: 'i18n_login_user_name_label'
                  })}
                />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_login_user_password_valid_label'
                    })
                  }
                ]
              })(
                <Input
                  prefix={<Icon type="lock" />}
                  type="password"
                  placeholder={formatMessage({
                    id: 'i18n_login_user_password_label'
                  })}
                />
              )}
            </FormItem>
            <FormItem className="clearfix">
              {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true
              })(
                <Checkbox className="text-secondary">
                  <FormattedMessage id="i18n_login_remember_me_label" />
                </Checkbox>
              )}
              <a className="float-right" href="#">
                <FormattedMessage id="i18n_login_forgot_password_label" />
              </a>
              <Button type="primary" htmlType="submit" className="w-100">
                <FormattedMessage id="i18n_login_label" />
              </Button>
              <span className="text-secondary">
                <FormattedMessage id="i18n_login_or_label" />
              </span>
              <Link to="/register" className="ml-1">
                <FormattedMessage id="i18n_login_register_now_label" />
              </Link>
            </FormItem>
            <FormItem />
          </Form>
        </Animate>
      </Fragment>
    )
  }
}

const Login = Form.create()(NormalLogin)
export default injectIntl(Login)
